$(function () {
    layui.config({
        base: '../../statics/common/'
    }).extend({
        soulTable: 'layui/soultable/ext/soulTable.slim'
    });
    layui.use(['form', 'layedit', 'laydate', 'element', 'table', 'soulTable'], function () {
        init(layui);
        layui.form.render();
    });
});

var viewer;
var deliveryFileIdTmp;
var vm = new Vue({
    el: '#rrapp',
    data: {
        q: {
            keyword: null
        },
        carUpdateId: 'carUpdateId_1',
        deliveryFileLstId : 'deliveryFileLstId_1',
        feeItemId: null,
        monthlyRentAdjust : 0,
        monthlyRent: '',
        coverCharge: '',
        order: {},
        deliveryFileLst: [],
        feeItemLst: [],
        usrLst: [],
        accessoryItems: []
    },
    created: function () {
        var _this = this;
        var param = parent.layer.boxParams.boxParams;
        var order = param.data;
        var orderCar = param.data.orderCar;
        _this.order = {
            id: order.id,
            orderCarIds: null,
            plan: order.plan,
            orderCar: {
                orderId: orderCar.orderId,
                rentType: orderCar.rentType,
                paymentMethod: orderCar.paymentMethod,
                insuranceItems: orderCar.insuranceItems,
                paymentDay: orderCar.paymentDay,
                paymentDayType: orderCar.paymentDayType,
                channelId: orderCar.channelId,
                channelName: orderCar.channelName,
                timeStartRent: orderCar.timeStartRent,
                timeFinishRent: orderCar.timeFinishRent,
                tenancy: orderCar.tenancy,
                tenancyType: orderCar.tenancyType,
                orderDesc: orderCar.orderDesc,
                timeDelivery: dateFormat(orderCar.timeDelivery||new Date().getTime()),
                swopOrderCarId: orderCar.id,
                deliveryOperationId: sessionStorage.getItem("userId"),
                deliveryOperationName: sessionStorage.getItem("username"),
                status: 1,
                deliveryFileLst: _this.deliveryFileLst
            }
        };
        _this.order.plan.id = null;
        _this.order.plan.code = null;
        _this.order.plan.orderCarId = null;
        _this.order.plan.orderCarCode = null;
        _this.order.plan.timeCreate = null;
        _this.order.plan.timeUpdate = null;
        _this.order.plan.brandId = null;
        _this.order.plan.brandName = null;
        _this.order.plan.seriesId = null;
        _this.order.plan.seriesName = null;
        _this.order.plan.modelId = null;
        _this.order.plan.modelName = null;
        _this.order.plan.balancePaymentLst = [];
        if ((orderCar.rentType === 1 || orderCar.rentType === 2) && _this.order.plan.coverCharge != null){
            _this.order.plan.monthlyRent = toMoney(Number(_this.order.plan.monthlyRent) - Number(_this.order.plan.coverCharge));
            _this.order.plan.coverCharge = toMoney(_this.order.plan.coverCharge);
        }
        $.get(baseURL + "sys/user/usrLst", function (r) {
            _this.usrLst = r.usrLst;
        });
        $.ajaxSettings.async = false;
        $.get(baseURL + "sys/dict/getInfoByType/accessoryItem", function (r) {
            _this.accessoryGroupList = r.dict;
            if (_this.accessoryGroupList != null && _this.accessoryGroupList.length > 0){
                var parent = $('#accessoryGroup');
                _this.accessoryGroupList.forEach(function (d) {
                    parent.append('<input type="checkbox" lay-filter="accessoryItems" v-model="accessoryItems" name="accessoryItems" value="'+d.value+'" lay-skin="primary" title="'+d.value+'">');
                });
            }
        });
        $.get(baseURL + "order/orderfeeitemdict/selectorByRentType/" + orderCar.rentType, function (r) {
            _this.feeItemLst = r.datas;
        });
        if (_this.feeItemLst == null){
            _this.feeItemLst = [];
        }
        for(var i = 0 ;i<_this.feeItemLst.length;i++) {
            if(_this.feeItemLst[i].fieldName === 'monthly_rent') {
                _this.feeItemLst.splice(i,1);
                i= i-1;
            }
            if(_this.feeItemLst[i].fieldName === 'cover_charge') {
                _this.feeItemLst.splice(i,1);
                i= i-1;
            }
        }
        $.ajaxSettings.async = true;
        // switch (parseInt(_this.order.rentType)) {
        //     case 1://经租
        //     case 3: //展示车
        //     case 4: {//试驾车
        //         _this.feeItemLst.push({id: 1, name: '保证金', fieldName: 'cash_deposit', defaultPaymentMethod: 5, multiple: true});
        //         break;
        //     }
        //     case 2:{//以租代购
        //         _this.feeItemLst.push({id: 2, name: '整备费', fieldName: 'servicing_fee', defaultPaymentMethod: 5, multiple: true});
        //         _this.feeItemLst.push({id: 4, name: '尾款', fieldName: 'balance_payment', defaultPaymentMethod: 5, multiple: true});
        //         break;
        //     }
        //     case 5: {//融租
        //         _this.feeItemLst.push({id: 3, name: '首付款', fieldName: 'down_payment', defaultPaymentMethod: 5, multiple: true});
        //         _this.feeItemLst.push({id: 4, name: '尾款', fieldName: 'balance_payment', defaultPaymentMethod: 5, multiple: true});
        //         break;
        //     }
        //     case 6: {//直购
        //         break;
        //     }
        //     default: {
        //     }
        // }
        // _this.feeItemLst.push({id: 5, name: '定金', fieldName: 'advance_deposit', defaultPaymentMethod: 5, multiple: true});
        // _this.feeItemLst.push({id: 6, name: '其他费用', fieldName: 'other_fee', defaultPaymentMethod: 5, multiple: true});
    },
    updated: function () {
        layui.form.render();
    },
    methods: {
        delDeliveryFile: function (id) {
            for(var i = 0 ;i<vm.deliveryFileLst.length;i++) {
                if(vm.deliveryFileLst[i].id === id) {
                    vm.deliveryFileLst.splice(i,1);
                    i= i-1;
                }
            }
        },
        selectCar: function () {
            var param = {
                brandId: '',
                seriesId: '',
                modelId: '',
            };
            var index = layer.open({
                title: "选择车辆",
                type: 2,
                area: ['80%', '80%'],
                boxParams: param,
                content: tabBaseURL + "modules/order/selectcar.html",
                end: function () {
                    layer.close(index);
                }
            });
        },
        addFeeItem: function () {
            if (vm.feeItemId == null || vm.feeItemId == ''){
                alert('请先选择费用项类型');
                return;
            }
            if (vm.order.plan.balancePaymentLst.filter(function (value) {
                return (value.money == null || String(value.money).length < 1)
                    ||(value.paymentMethod == null || !(/[1-5]{1}/).test(value.paymentMethod))
                    ||(value.timePayment1st == null || value.timePayment1st == '');
            }).length > 0){
                alert('有未完善费用项，请先完善后再添加');
                return;
            }
            var feeItem = vm.feeItemLst.filter(function (f) {
                return f.id == vm.feeItemId;
            })[0];
            var serializeId = 0;
            if(vm.order.plan.balancePaymentLst.length > 0){
                vm.order.plan.balancePaymentLst.forEach(function (value) {
                    if (value.serializeId > serializeId) serializeId = value.serializeId;
                })
            }
            var item = {
                serializeId:serializeId+1,
                elid: 'serializeId_'+(serializeId+1),
                typeFieldName:feeItem.fieldName,
                typeFieldDesc:feeItem.name,
                multiple:feeItem.multiple,
                money:'',
                paymentMethod:feeItem.defaultPaymentMethod,
                timePayment1st:''
            };
            vm.order.plan.balancePaymentLst.push(item);
            vm.reloadFeeItem();
        },
        reloadFeeItem: function () {
            layui.table.reload('feeLstid', {
                page: {
                    curr: getCurrPage('feeLstid', vm.order.plan.balancePaymentLst.length)
                },
                data: vm.order.plan.balancePaymentLst});
        },
        feeItemDelectObj: function (obj) {
            layer.confirm('确认删除该条数据？', function(index){
                var serializeId = obj.data.serializeId;
                obj.del();
                layer.close(index);
                for(var i = 0 ;i<vm.order.plan.balancePaymentLst.length;i++) {
                    if(vm.order.plan.balancePaymentLst[i].serializeId === serializeId) {
                        vm.order.plan.balancePaymentLst.splice(i,1);
                        i= i-1;
                        break;
                    }
                }
                vm.reloadFeeItem();
            });
        },
        editfeeItemlistener: function (obj) {
            //
            var field = obj.field;
            var value = obj.value;
            var regNumber = /^[0-9]+\.?[0-9]*$/;
            var regInt = /^[0-9]*$/;
            var v;
            if (!regNumber.test(value)) {
                alert("请输入正确的金额");
                v = '';
            }else {
                if (field === 'money') {//分期金额
                    v = Number(value).toFixed(2);
                }
            }
            vm.order.plan.balancePaymentLst.forEach(function (value) {
                if (value.serializeId === obj.data.serializeId) value.money = v;
            });
            vm.reloadFeeItem();
        },
        saveOrUpdate: function (event) {
            if (vm.order.plan.balancePaymentLst.filter(function (value) {
                return (value.money == null || String(value.money).length < 1)
                    ||(value.paymentMethod == null || !(/[1-5]{1}/).test(value.paymentMethod))
                    ||(value.timePayment1st == null || value.timePayment1st == '');
            }).length > 0){
                alert('有未完善费用项');
                return;
            }
            PageLoading();
            vm.order.orderCar = Object.assign({}, vm.order.orderCar, {
                brandId: vm.order.plan.brandId,
                brandName: vm.order.plan.brandName,
                seriesId: vm.order.plan.seriesId,
                seriesName: vm.order.plan.seriesName,
                modelId: vm.order.plan.modelId,
                modelName: vm.order.plan.modelName
            });
            vm.order.orderCar.accessoryItemsName = jointStr(',', vm.accessoryItems);
            if (vm.accessoryGroupList != null && vm.accessoryGroupList.length > 0){
                var code = [];
                vm.accessoryGroupList.forEach(function (ins) {
                    if ($.inArray(ins.value, vm.accessoryItems) >= 0) {
                        code.push(ins.code);
                    }
                });
                vm.order.orderCar.accessoryItems = jointStr(',', code);
            }
            vm.order.plan.monthlyRentAdjust = vm.monthlyRentAdjust;
            var param = JSON.parse(JSON.stringify(vm.order));
            if (vm.monthlyRentAdjust == 1){
                param.plan.monthlyRent = vm.monthlyRent||0;
                param.plan.coverCharge = vm.coverCharge||0;
                if (vm.order.orderCar.rentType === 1 || vm.order.orderCar.rentType === 2){
                    param.plan.monthlyRent = toMoney(Number(param.plan.monthlyRent) + Number(param.plan.coverCharge));
                }
            }
            $.ajax({
                type: "POST",
                url: baseURL + 'order/order/delivercar',
                contentType: "application/json",
                data: JSON.stringify(param),
                success: function (r) {
                    RemoveLoading();
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            closePage();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        downDoc: function (fileName, url) {
            var uri = baseURL + 'file/download?uri='+url+"&fileName="+fileName;
            window.location.href = uri;
        },
        showDoc: function (fileName, url) {
            if (viewer != null){
                viewer.close();
                viewer = null;
            }
            viewer = new PhotoViewer([
                {
                    src: fileURL+url,
                    title: fileName
                }
            ], {
                appendTo:'body',
                zIndex:99891018
            });
        }
    }
});

function init(layui) {
    initTable(layui.table, layui.soulTable);
    initDate(layui.laydate);
    initEventListener(layui);
    initData();
    initUpload(layui.upload);
}

function initUpload(upload) {
    Upload({
        elid: 'addDeliveryFile',
        edit: true,
        fileLst: vm.deliveryFileLst,
        param: {'path':'order-delivery'},
        fidedesc: '交车附件'
    }).initView();
}

function initData() {

}

function initEventListener(layui) {
    initClick();
    initChecked(layui.form);
    initVerify(layui.form);
}

function initVerify(form) {
    form.verify({
        validate_deliveryOperationId: function (value, item) { //value：表单的值、item：表单的DOM对象
            if (value == null || value == '') {
                return "请选择交车工作人员";
            }
        },
        validate_carId: function (value, item) { //value：表单的值、item：表单的DOM对象
            if (value == null || value == '') {
                return "请选择车辆";
            }
        },
        validate_monthlyRent: function (value, item) { //value：表单的值、item：表单的DOM对象
            if (value == null || value == '') {
                return "请输入月租金额";
            }
        }
    });
}

function initChecked(form) {
    form.on('submit(save)', function () {
        vm.saveOrUpdate();
        return false;
    });

    form.on('checkbox(accessoryItems)', function (data) {
        var item = data.value;
        var checked = data.elem.checked;
        if (checked){
            if ($.inArray(item, vm.accessoryItems) >= 0) {
            }else{
                vm.accessoryItems.push(item);
            }
        } else {
            if ($.inArray(item, vm.accessoryItems) >= 0) {
                for (var i = 0; i < vm.accessoryItems.length; i++) {
                    if (vm.accessoryItems[i] == item) {
                        vm.accessoryItems.splice(i, 1);
                        i = i - 1;
                    }
                }
            }
        }
    });

    form.on('select(deliveryOperation)', function (data) {
        var usrid = data.value;
        vm.order.orderCar.deliveryOperationId = usrid;
        var obj = vm.usrLst.filter(function (obj) {
            return obj.userId == usrid;
        })[0];
        if (obj != null){
            vm.order.orderCar.deliveryOperationName = obj.username;
        }else {
            vm.order.orderCar.deliveryOperationName = '';
        }
        vm.deliveryFileLst.forEach(function (value) {
            value.operationId = usrid;
            value.operationName = vm.order.orderCar.deliveryOperationName;
        });
    });

    form.on('radio(monthlyRentAdjust)', function (data) {
        vm.monthlyRentAdjust = data.value;
    });

    form.on('select(feeItem)', function (data) {
        vm.feeItemId = data.value;
    });

    form.on('select(balancePaymentMethod)',function (data) {
        var serializeId = data.elem.attributes.sid.value;
        vm.order.plan.balancePaymentLst.forEach(function (value) {
            if (value.serializeId == serializeId) {
                value.paymentMethod = data.value;
            }
        });
    });
}

function initClick() {
    $("#closePage").on('click', function () {
        closePage();
    });
}

function initTable(table, soulTable) {
    table.render({
        id: 'feeLstid',
        elem: '#feeLst',
        data: vm.order.plan.balancePaymentLst,
        cols: [[
            {field:'typeFieldDesc', title: '类型'},
            {field:'money', title: '金额/元', edit: 'text', event: 'money'},
            {field:'paymentMethod', title: '付款方式', templet: '#selectPaymentMethod'},
            {field:'timePayment1st', title: '第一次付款日期', event: 'selectTimePayment1st', templet: function (d) {
                    var txt = d.timePayment1st;
                    if ((/\d+/).test(txt)){
                        txt = isEmpty(dateFormatYMD(txt));
                    }else txt = '请选择第一次付款日期';
                    return txt;
                }},
            {title: '操作', width: 120, templet: '#feeItemBarTpl', fixed: "right", align: "center"}
        ]],
        page: true,
        limits: [5, 8, 15],
        limit: 5,
        done: function (res, curr, count) {
            $('td[data-field="paymentMethod"]>div>select').each(function () {
                var serializeId = this.attributes.sid.value;
                var value = vm.order.plan.balancePaymentLst.filter(function (value) {
                    return value.serializeId == serializeId;
                })[0].paymentMethod;
                $(this).val(value);
            });
            layui.form.render('select');
            $('td[data-field="timePayment1st"]').prepend('<div style="position: absolute;line-height: 0;background-color: rgba(0, 0, 0, 0);text-indent: -99999px;width: 100%;height: 100%;z-index: 999999"></div>');
        }
    });

    initTableEvent(table);
    initTableEditListner(table);
}

function initTableEditListner(table) {
    table.on('edit(feeLst)', function(obj){
        vm.editfeeItemlistener(obj);
    });
}

function initTableEvent(table) {
    table.on('tool(feeLst)', function (obj) {
        var layEvent = obj.event;
        var data = obj.data;
        if (layEvent === 'delect') {
            vm.feeItemDelectObj(obj);
        }else if (layEvent === 'selectTimePayment1st') {
            var txt = '';
            if ((/\d+/).test(data.timePayment1st)){
                txt = isEmpty(dateFormatYMD(data.timePayment1st));
            }else {
                var now = new Date();
                txt = now.format('yyyy-MM-dd');
            }
            this.firstChild.textContent = txt;
            layui.laydate.render({
                elem: this.firstChild,
                trigger: 'click',
                closeStop: this,
                isInitValue: false,
                value: txt,
                btns: ['now', 'confirm'],
                show: true,
                done: function (value, date) {
                    data.timePayment1st = new Date(value).getTime();
                    vm.order.plan.balancePaymentLst.forEach(function (value) {
                        if (value.serializeId === data.serializeId) value.timePayment1st = data.timePayment1st;
                    });
                    obj.update(data);
                    $('td[data-field="paymentMethod"]>div>select').each(function () {
                        var serializeId = this.attributes.sid.value;
                        var value = vm.order.plan.balancePaymentLst.filter(function (value) {
                            return value.serializeId == serializeId;
                        })[0].paymentMethod;
                        $(this).val(value);
                    });
                    layui.form.render('select');
                }
            });
        }else if (layEvent === 'money') {
            tableEditMaxlength('money', 10);
            tableEditOninputNum('money');
        }
    });
}

function initDate(laydate) {
    laydate.render({
        elem: '#mileageNextDate',
        trigger: 'click',
        done: function (value) {
            vm.order.orderCar.mileageNextDate = value;
        }
    });

    laydate.render({
        elem: '#timeDelivery',
        trigger: 'click',
        type: 'datetime',
        done: function (value) {
            vm.order.orderCar.timeDelivery = value;
        }
    });
}

function closePage() {
    parent.vm.isClose = true;
    var index = parent.layer.getFrameIndex(window.name);
    parent.vm.reload();
    parent.layer.close(index);
}
